package api

import (
	"gitee.com/go-course/go12/devcloud-mini/cmdb/apps/secret"
	"github.com/emicklei/go-restful/v3"
	"github.com/infraboard/mcube/http/restful/response"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	oteltrace "go.opentelemetry.io/otel/trace"
)

func (h *handler) ListSecret(r *restful.Request, w *restful.Response) {
	// 埋点，添加自定义trace
	// 全局providre, ioc SetTracerProvider 已经设置好了 全局provider
	p := otel.GetTracerProvider()
	_, span := p.Tracer("cmdb").Start(r.Request.Context(), "ListSecret",
		oteltrace.WithAttributes(attribute.String("username", "admin")),
	)
	defer span.End()

	// ctx 需要继续往后传递(这个context里面包含 trace id)
	// 因为没有后续逻辑 这里丢弃了context

	response.Success(w, "test")
}

func (h *handler) DescribeSecret(r *restful.Request, w *restful.Response) {
	ins, err := h.controller.DescribeSecret(r.Request.Context(), &secret.DescribeSecretRequest{
		Id: r.PathParameter("id"),
	})
	if err != nil {
		response.Failed(w, err)
	}
	response.Success(w, ins)
}

func (h *handler) CreateSecret(r *restful.Request, w *restful.Response) {
	response.Success(w, "test")
}

// 使用云商账号凭证 来实现资源同步
// 我们有多个返回, 需要使用 websocket 来 把当前的 http链接 升降成 websocket协议(tcp封装)
func (h *handler) SyncResource(r *restful.Request, w *restful.Response) {
	// w http.ResponseWriter 浏览器处理不了 之定义header
	socket, err := h.Upgrader().Upgrade(w, r.Request, nil)
	if err != nil {
		response.Failed(w, err)
	}
	defer socket.Close()

	// 当socket 建立成功后, 把鉴权的逻辑搬过来
	// mcenter.Token().ValidateToken()
	// mcenter.Permission.CheckPermission()

	req := &secret.SyncResourceRequest{
		Id: r.PathParameter("id"),
	}
	err = h.controller.SyncResource(r.Request.Context(), req, func(sr *secret.SyncResponse) {
		err := socket.WriteJSON(sr)
		if err != nil {
			h.log.Error().Msgf("websocket write error, %s", err)
		}
	})
	if err != nil {
		socket.WriteJSON(err.Error())
	}
}
